﻿using System;
using System.Web.UI.WebControls;
using Lswweb.Model;
using Lswweb.Domain;
using Lswweb.Controls;

namespace Lswweb.Controls
{
    public class UserProfileEdit:SkinnedWebControl
    {
        #region 成员字段和构造方法

        private UserProfile userProfile;
        private Label lbName;
        private Button btnConfirm;

        #endregion

        #region 初始化控件

        protected override void InitializeSkin(System.Web.UI.Control skin)
        {
            userProfile = (UserProfile)skin.FindControl("userProfile");
            lbName = (Label)skin.FindControl("lbName");
            btnConfirm = (Button)skin.FindControl("btnConfirm");

            btnConfirm.Click += new EventHandler(btnConfirm_Click);


            if (this.User == null)
            {
                SiteContext.RenderMessage(ExceptionType.UserNotFound);
                return;
            }
            else
            {
                userProfile.ProfileInfo = this.User.Profile;

                if (lbName != null)
                    lbName.Text = this.User.LoginName;
            }
        }

        void btnConfirm_Click(object sender, EventArgs e)
        {
            UserProfileInfo profileInfo = userProfile.ProfileInfo;
            profileInfo.UserId = User.Id;
            Users.UpdateProfile(profileInfo);
        }

        #endregion

        #region 属性

        private int userId = -1;
        private int UserId
        {
            get 
            {
                if (userId == -1)
                    return SiteContext.Current.Id;

                return this.userId;
            }
        }

        private UserInfo user;
        public UserInfo User
        {
            get
            {
                if (this.user == null)
                {
                    if (UserId == -1 || !SiteContext.Current.User.IsAdmin)
                        user = SiteContext.Current.User;
                    else
                        user = Users.GetUser(UserId);
                }

                return user;   
            }
        }

        #endregion

        protected override string DefaultSkinFilename
        {
            get { return "User/UserProfileEdit.ascx"; }
        }
    }
}
